package com.jstyle.jclife.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.HeartDetailAdapter;
import com.jstyle.jclife.adapter.HistoryShowAdapter;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ResolveData;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HeartHistoryWeekFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HeartHistoryWeekFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_sleep_week_pre)
    ImageView btSleepWeekPre;
    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.bt_sleep_week_next)
    ImageView btSleepWeekNext;
    @BindView(R.id.LineChartView_heart_week)
    LineChartView LineChartViewHeartWeek;
    @BindView(R.id.RecyclerView_heart_total)
    RecyclerView RecyclerViewHeartTotal;
    @BindView(R.id.bt_thisWeek)
    Button btThisWeek;
    @BindView(R.id.RecyclerView_heartWeek)
    RecyclerView RecyclerViewHeartWeek;
    Unbinder unbinder;
    @BindView(R.id.tv_noData)
    Button tvNoData;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private String[] thisWeek;
    private boolean isBusy;
    private static final String TAG = "HeartHistoryWeekFragmen";
    private HashMap<String, Integer> maxHrMap = new HashMap<>();
    private HashMap<String, Integer> staticHrMap = new HashMap<>();
    private HashMap<String, Integer> avgHrMap = new HashMap<>();
    private List<String> listContent;
    private HistoryShowAdapter historyShowAdapter;
    private int MHR;
    private Typeface mFace;

    public HeartHistoryWeekFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HeartHistoryWeekFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HeartHistoryWeekFragment newInstance(String param1, String param2) {
        HeartHistoryWeekFragment fragment = new HeartHistoryWeekFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_heart_history_week, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        mFace = Typeface.createFromAsset(getActivity().getAssets(),"Brandon_reg.otf");

        getMaxHr();

        thisWeek = DateUtil.getTodayWeek(0);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHeartWeek.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        ColorDrawable colorDrawable = new ColorDrawable();
        colorDrawable.setColor(Color.DKGRAY);
        dividerItemDecoration.setDrawable(colorDrawable);
        RecyclerViewHeartWeek.addItemDecoration(dividerItemDecoration);
        FlexboxLayoutManager layoutManager2 = new FlexboxLayoutManager(getActivity());
        listContent = new ArrayList<>();
        listContent.add(getString(R.string.Minimum_HR));
        listContent.add(getString(R.string.Maximum_HR));
        historyShowAdapter = new HistoryShowAdapter(listContent);
        RecyclerViewHeartTotal.setAdapter(historyShowAdapter);
        RecyclerViewHeartTotal.setLayoutManager(layoutManager2);
        findData();
    }

    private void findData() {
        String showDate = DateUtil.getShowWeekDate(getActivity(), thisWeek[0]) + "-" + DateUtil.getShowWeekDate(getActivity(), thisWeek[6]);
        btSleepWeekDate.setText(showDate);
        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        btSleepWeekNext.setEnabled(true);
        for (int i = 0; i < thisWeek.length - 1; i++) {
            if (thisWeek[i].equals(nowDate)) {
                btSleepWeekNext.setEnabled(false);
            }
        }
        isBusy = true;
        maxHrMap.clear();
        staticHrMap.clear();
        avgHrMap.clear();
        mergeHeartData();
    }

    private void mergeHeartData() {
        heartRange = new int[5];
        lastWeekHeartRange = new int[5];
        List<Observable<Integer>> observables = new ArrayList<>();
        String[] lastWeek = DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
        for (String date : lastWeek) {
            observables.add(getLastWeekDayObservable(date));
        }
        for (String date : thisWeek) {
            observables.add(getDayObservable(date));
        }
        showLoadingDialog();
        Observable.merge(observables).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {
                disMissLoadingDialog();
                isBusy = false;
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                disMissLoadingDialog();
                //setRecycleViewData();
                setDayRecycleViewData();
                setHeartChartViewData();
                isBusy = false;
            }
        });
    }

    private void setDayRecycleViewData() {


        HeartDetailAdapter heartDetailAdapter = new HeartDetailAdapter(heartRange, lastWeekHeartRange, HeartDetailAdapter.DATA_WEEK);
        RecyclerViewHeartWeek.setAdapter(heartDetailAdapter);

    }

    private void setHeartChartViewData() {
        boolean hasData=false;
        for (Map.Entry<String, Integer> entry : avgHrMap.entrySet()) {
            int hr = entry.getValue();
            if (hr != 0){
                hasData=true;
                break;
            }
        }
        if(hasData){
            tvNoData.setVisibility(View.GONE);
            LineChartViewHeartWeek.setVisibility(View.VISIBLE);
        }else{
            tvNoData.setVisibility(View.VISIBLE);
            LineChartViewHeartWeek.setVisibility(View.GONE);
        }
      int max = 0;
        int min = 300;
        for (Map.Entry<String, Integer> entry : maxHrMap.entrySet()) {
            int hr = entry.getValue();
            max = Math.max(max, hr);
        }
        for (Map.Entry<String, Integer> entry : staticHrMap.entrySet()) {
            int hr = entry.getValue();
            if (hr != 0) min = Math.min(min, hr);
        }
        int avgHr = min == 300 ? 0 : min;
        String label=" "+getResources().getString(R.string.hr_laber);
        List<String> listHeart = new ArrayList<>();//总计列表
        listHeart.add(avgHr + label);
        listHeart.add(max + label);
        historyShowAdapter.setStepData(listHeart);
        float top=0;
        if(max%10==0){
            top=max;
        }else{
            top=(((int)max/10)+1)*10;
        }
        ChartDataUtil.initDataChartView(LineChartViewHeartWeek, -0.5f, top+10, 6.5f, 40);
        LineChartViewHeartWeek.setLineChartData(ChartDataUtil.getWeekHeartHistoryChart(getActivity(), thisWeek, avgHrMap,mFace,top));

    }

    private Observable<Integer> getDayObservable(final String date) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                List<HeartData> heartDataList = HeartDataDaoManager.queryDayData(date);
                getHeartRate(heartDataList, date);

                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread());

    }

    private Observable<Integer> getLastWeekDayObservable(final String date) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                List<HeartData> heartDataList = HeartDataDaoManager.queryDayData(date);
                getLastWeekHeartRange(heartDataList, date);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread());

    }

    private void getLastWeekHeartRange(List<HeartData> heartDataList, String date) {
        for (HeartData data : heartDataList) {
            int value = data.getHeart();
            if (value != 0) {
                int range=ResolveData.getHeartRange(value, MHR);
                if(range!=-1)lastWeekHeartRange[range]++;

            }
        }
    }

    int[] heartRange;
    int[] lastWeekHeartRange;

    private void getHeartRate(List<HeartData> heartDataList, String date) {
        float totalHR = 0;
        float count = 0;
        int maxHr = 0;
        int staticHr = 300;
        for (HeartData data : heartDataList) {
            int value = data.getHeart();
            if (value != 0) {
                count++;
                totalHR += value;
                staticHr = Math.min(staticHr, value);
                maxHr = Math.max(maxHr, value);
                int range=ResolveData.getHeartRange(value, MHR);
                if(range!=-1)heartRange[range]++;

            }
        }
        int hr = count == 0 ? 0 : (int) (totalHR / count);
        avgHrMap.put(date, hr);
        maxHrMap.put(date, maxHr);
        staticHrMap.put(date, staticHr == 300 ? 0 : staticHr);
    }

    private void getMaxHr() {
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        String birthday = userInfo.getBirthday();
        int userYear = Integer.parseInt(birthday.split("-")[0]);
        Calendar calendar = Calendar.getInstance();
        int age = calendar.get(Calendar.YEAR) - userYear;
        MHR = 220 - age;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_sleep_week_pre, R.id.bt_sleep_week_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sleep_week_pre:
                thisWeek = DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
                findData();
                break;
            case R.id.bt_sleep_week_next:
                thisWeek = DateUtil.getWeekString(thisWeek[6], DateUtil.nextWeek);
                findData();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
